package tools

import (
	"exam-app/api/global"
	"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
)

type Consul struct {
	Host string
	Port int
}

func NewConsul(host string, port int) *Consul {
	return &Consul{
		Host: host,
		Port: port,
	}
}
func (c *Consul) ConsulRegister(name string, address string, port int, tags []string) error {
	registration := new(api.AgentServiceRegistration)
	registration.ID = uuid.NewString()
	registration.Name = name
	registration.Address = address
	registration.Port = port
	registration.Tags = tags
	err := global.ConsulClient.Agent().ServiceRegister(registration)
	if err != nil {
		return err
	}
	return nil
}
func (c *Consul) ConsulFilter(name string) (map[string]*api.AgentService, error) {

	sprintf := fmt.Sprintf(`Service == "%s"`, name)
	filter, err := global.ConsulClient.Agent().ServicesWithFilter(sprintf)
	if err != nil {
		return nil, err
	}
	return filter, nil
}
